package com.ruoyi.web.controller.system;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.vo.ActMaterialVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ActMaterial;
import com.ruoyi.system.service.IActMaterialService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 参赛其他材料提交Controller
 *
 * @author xuyk
 * @date 2022-03-13
 */
@Controller
@RequestMapping("/system/material")
public class ActMaterialController extends BaseController
{
    private String prefix = "system/material";

    @Autowired
    private IActMaterialService actMaterialService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Value("${ruoyi.materialExportName:其他材料}")
    private String materialExportName;

    @RequiresPermissions("system:material:view")
    @GetMapping()
    public String material(ModelMap mmap)
    {
//        boolean addPermission = true;
//        SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
//        if(dept != null){
//            if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
//                //非院系人员暂时没有添加权限
//                addPermission = false;
//            }
//        }

        boolean canOperation = getUserOperationPower();
        if(!canOperation){
            SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
            if(dept == null){
                return null;
            }
            if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
                canOperation = true;
            }
        }
        mmap.put("canOperation",canOperation);

        mmap.put("user",getSysUser());
        return prefix + "/material";
    }

    /**
     * 查询参赛其他材料提交列表
     */
    @RequiresPermissions("system:material:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ActMaterial actMaterial)
    {
        SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
        if(dept == null){
            return null;
        }

        if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
            actMaterial.setAllSelectPerm(true);
        }else{
            actMaterial.setFacultyId(sysDeptService.getUserFaculty(getSysUser()).getDeptId());
        }
        startPage();
        List<ActMaterial> list = actMaterialService.selectActMaterialList(actMaterial);
        return getDataTable(list);
    }

    /**
     * 导出参赛其他材料提交列表
     */
    @RequiresPermissions("system:material:export")
    @Log(title = "参赛其他材料提交", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ActMaterial actMaterial)
    {
        SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
        if(dept == null){
            return null;
        }
        if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
            actMaterial.setAllSelectPerm(true);
        }else{
            actMaterial.setFacultyId(sysDeptService.getUserFaculty(getSysUser()).getDeptId());
        }
        List<ActMaterial> list = actMaterialService.selectActMaterialList(actMaterial);
        for(ActMaterial item : list){
            String schoolName = item.getSchool();
            String beginChar = schoolName.substring(0,1);
            if("0123456789".indexOf(beginChar) > -1){
                String begin = schoolName.substring(0,6);
                begin = begin.replaceAll("[0-9|-]","");
                schoolName = begin + schoolName.substring(6);
            }
            item.setSchool(schoolName);
        }
        ExcelUtil<ActMaterial> util = new ExcelUtil<ActMaterial>(ActMaterial.class);
        return util.exportExcel(list, this.materialExportName);
    }

    /**
     * 新增参赛其他材料提交
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        // 获取当前用户的学校和院系
        //getUserId()
        mmap.put("school",sysDeptService.getUserSchools(getSysUser()));
        mmap.put("faculty",sysDeptService.getUserFaculty(getSysUser()));
        mmap.put("userName",getSysUser().getUserName());
        return prefix + "/add";
    }

    /**
     * 新增保存参赛其他材料提交
     */
    @RequiresPermissions("system:material:add")
    @Log(title = "参赛其他材料提交", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ActMaterial actMaterial)
    {
        actMaterial.setUserId(getUserId());
        actMaterial.setUserName(getSysUser().getUserName());
        actMaterial.setSchoolId(sysDeptService.getUserSchools(getSysUser()).getDeptId());
        actMaterial.setFacultyId(sysDeptService.getUserFaculty(getSysUser()).getDeptId());
        actMaterial.setCreateBy(getLoginName());
        return toAjax(actMaterialService.insertActMaterial(actMaterial));
    }

    /**
     * 修改参赛其他材料提交
     */
    @RequiresPermissions("system:material:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ActMaterial actMaterial = actMaterialService.selectActMaterialById(id);
        mmap.put("actMaterial", actMaterial);
        return prefix + "/edit";
    }

    /**
     * 修改保存参赛其他材料提交
     */
    @RequiresPermissions("system:material:edit")
    @Log(title = "参赛其他材料提交", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ActMaterial actMaterial)
    {
        actMaterial.setUpdateBy(getLoginName());
        return toAjax(actMaterialService.updateActMaterial(actMaterial));
    }

    /**
     * 删除参赛其他材料提交
     */
    @RequiresPermissions("system:material:remove")
    @Log(title = "参赛其他材料提交", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(actMaterialService.deleteActMaterialByIds(ids));
    }

    @Autowired
    private ISysConfigService configService;

    private boolean getUserOperationPower(){
        String dateStr = configService.selectConfigByKey("game.end.time");
        if(StringUtils.isNotBlank(dateStr)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try{
                Date endTime = sdf.parse(dateStr);
                Date now = new Date();
                if(now.compareTo(endTime) >= 0){
                    return false;
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return  true;
    }
}
